package com.zzx.auth.oauth2;

import com.zzx.auth.exception.GlobalOauth2ExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

/**
 * OAuth 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
    /** 密码加密编码器*/
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    UserDetailServiceImpl userDetailService;

    /** token的存储*/
    @Autowired
    TokenStore tokenStore;

    /** jwt 转换器 */
    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    /** 密码模式需要添加管理器*/
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Bean
    public ClientDetailsService clientDetailsService() {
        // 基于JDBC
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 用户授权操作记录 - 授权码模式才用
     */
/*    @Bean
    public UserApprovalHandler userApprovalHandler() {
        ApprovalStoreUserApprovalHandler userApprovalHandler = new ApprovalStoreUserApprovalHandler();
        userApprovalHandler.setApprovalStore(approvalStore());
        userApprovalHandler.setClientDetailsService(clientDetailsService());
        userApprovalHandler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
        return userApprovalHandler;
    }


    @Bean
    public ApprovalStore approvalStore() {
        return new JdbcApprovalStore(dataSource());
    }*/
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                // 允许表单登录
                .allowFormAuthenticationForClients()
                // 密码加密编码器
                .passwordEncoder(passwordEncoder)
                // 允许所有的checkToken请求
                .checkTokenAccess("permitAll()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 基于内存配置
//        clients
//                .inMemory()
//                .withClient("client") // client
//                .secret(passwordEncoder.encode("123456"))
//                .authorizedGrantTypes("password") // 认证模式
//                .scopes("app") // 客户端能使用的范围
//                .accessTokenValiditySeconds(60 * 60 * 24 * 30); // 令牌有效期 秒; // 回调授权码 url
        // OAuto2的客户端配置 - 基于 JDBC
        clients.withClientDetails(clientDetailsService());
    }


    /**
     * 配置令牌
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                // 认证管理器 - 在密码模式必须配置
                .authenticationManager(authenticationManager)
                // 自定义校验用户service
                .userDetailsService(userDetailService)
                // 是否能重复使用 refresh_token
                .reuseRefreshTokens(false)
                .exceptionTranslator(new GlobalOauth2ExceptionTranslator());
        // 设置令牌增强 JWT 转换
        TokenEnhancerChain enhancer = new TokenEnhancerChain();
        enhancer.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        endpoints.tokenEnhancer(enhancer);
    }


}
